<?php


namespace App\Services;

use App\Models\MemberOther;
use App\Models\Order;
use App\Models\ShopUser;
use Illuminate\Support\Facades\Redis;
use App\Exceptions\BaseException;
/**
 *
 *公证接口对接
 */

class NotarizeService
{
    /**
     * 请求日志
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function requestLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::debug($message,$content);
    }

    /**
     * 获取accessToken
     * @return array
     */
    public static function getAccessToken(){
        $url = config('notarize.apiUrl').'/login';
        $param = [
            'corp_name'=>config('notarize.name'),
            'corp_pwd'=>config('notarize.secret'),
        ];
      //  $data = Redis::get('notarize_access_token');
//        if($data){
//           return $data;
//        }
        $result = http_post($url,$param);
        $result = json_decode($result,true);
        if (isset($result['status'])&&$result['status']=='200') {
            Redis::setex('notarize_access_token',7200,$result['data']);
           return $result['data'];
        }else{
            return false;
        }
    }


    /**
     * 上传订单基本信息
     * @param $code
     * @return array
     */
    public static function uploadOrderInfo($order){
        $accessToken = self::getAccessToken();
//        $order = Order::from('sp_order_2 as o')->where('o.id',$order_id)
//            ->leftjoin('sp_order_credit as c','c.order_id','o.id')
//            ->leftjoin('sp_member_2 as u','o.uid','u.id')
//            ->leftjoin('sp_shop_user_2 as su','o.seller_id','su.member_id')
//            ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
//            ->leftjoin('sp_goods_2 as g','og.goods_id','g.id')
//            ->select(
//                'o.id','o.trade_no','o.begin_time','o.zulinbao_order_id','o.end_time','o.pact_url_3','o.pact_url','o.uid','o.seller_id','o.is_insurance_choose',
//                'o.flow_id','o.mobile','o.user_email','o.sign_num','o.address','o.rent_total','o.month_total','o.amount','o.realname','o.rent_total',
//                'o.foregift','o.status','o.prov','o.city','o.area','o.sign_status','o.is_rent_choose'
//                ,'c.platformLoanNo','o.create_time'
//                ,'u.ant_user_id','u.mobile as user_mobile','u.id as x_user_id','u.cert_name','u.user_id','u.cert_no','u.esign_user_id'
//                ,'u.idcard_front','u.idcard_back','og.id as order_goods_id ','og.pact_type','og.is_buy_out','og.goods_title','og.setmeal_title',
//                'og.lease_set','og.setmeal_price','og.setmeal_foregift','o.prepayment_total',
//                'og.goods_id','og.setmeal_id','og.id as order_goods_id','og.spec_id','og.lease_price','og.lease_time','og.website_price','og.start_date'
//                ,'su.mechanism','su.faname','su.shopname','su.contact_tel','su.company','su.company_area','su.companyid','su.id as shop_user_id'
//                ,'su.ant_user_id as mer_ant_id','o.sign_no','su.esign_seal_id','su.ant_seal_id','o.prepayment_total' ,'g.new_grade')
//            ->first();
//        $order = $order ? $order->toArray() : [];

        if(!$order){
            return false;
        }

        if(!strstr($order['address'],'省')||!strstr($order['address'],'市')){
            $order['address']=$order['prov'].$order['city'].$order['area'].$order['address'];
        }
        // dd($accessToken);
        //上传个人信息
        $url = config('notarize.apiUrl').'/bussiness/customerInfo';
        $customer[] =[
            "customer_name"=>$order['cert_name'],
//            "nation"=>'汉',
//            "id_address"=>"aaaa",
            "address"=> $order['address'],
            "mobile_phone"=>$order['user_mobile'],
            "id_no"=>$order['cert_no'],
        ];
        $param = [
            "contract_id"=>$order['trade_no'].'003',
            "customers"=>$customer,
            "callback_url"=>config('alipay.callbackDomain').'/Alipay/Notice/notarizeNotary',
        ];
        //上传身份证
        $result = http_post($url,json_encode($param),['Content-type: application/json;charset=UTF-8','token:'.$accessToken]);
        $result = json_decode($result,true);
        self::requestLog('公证个人信息上传',$param,$result);

        if(!isset($result['status'])||$result['status']!='200'){
            throw new BaseException($result['msg']??'无法公证');
        }
        $orderData=$result['data'];


        if($orderData['contract_id']){
            Order::where('id',$order['id'])->update(['contract_id'=>$orderData['contract_id']]);
        }else{
        $contract_id=Order::where('id',$order['id'])->value('contract_id');
        $orderData['contract_id']=$contract_id;
        }
        $url = config('notarize.apiUrl').'/bussiness/attachment_idcard_push';//上传身份证
        $param =[
            "contract_id"=>$orderData['contract_id'],
            "userIdNo"=>$order['cert_no'],
            "idcard_front"=>config('alipay.oss.imgHost').$order['idcard_front'],
            "idcard_back"=> config('alipay.oss.imgHost').$order['idcard_back'],
        ];
        $result = http_post($url,json_encode($param),['Content-type: application/json;charset=UTF-8','token:'.$accessToken]);
        $result = json_decode($result,true);
        self::requestLog('公证身份证信息上传',$param,$result);
        if($result['status']!=200){
            throw new BaseException($result['msg']);
        }
        $url = config('notarize.apiUrl').'/bussiness/attachment_contract_sign';
        $param =[
            "contract_id"=>$orderData['contract_id'],
            "contract_file_url"=>config('alipay.oss.imgHost').$order['pact_url'],
            "contract_name"=>'都来租物租赁合同',
            "interest_rate_fixed"=>'0.06%',
            "contract_amount"=>$order['pact_type']==1?bcadd($order['rent_total'],$order['setmeal_price']).'元':$order['rent_total'],
            "loan_starttime"=>date('Y-m-d',strtotime($order['begin_time'])),
            "loan_endtime"=>date('Y-m-d',strtotime($order['end_time'])),
            "loan_term_type"=>'count',
            "loan_duration"=>$order['month_total'],
            "pay_day"=>date('d',strtotime($order['begin_time'])),
            "contract_sign_date"=>date('Y-m-d',time()),
            "rate_type"=>'01',
            "goods_name"=>$order['goods_title'].$order['setmeal_title'],
            "goods_price"=>$order['website_price'],
            "rental"=> $order['rent_total'],
            "retention_price"=> $order['pact_type']==1?$order['setmeal_price'].'元':0,
        ];
        $result = http_post($url,json_encode($param),['Content-type: application/json;charset=UTF-8','token:'.$accessToken]);
        $result = json_decode($result,true);
        self::requestLog('公证合同信息上传',$param,$result);

        if($result['status']!=200){
            throw new BaseException($result['msg']);
        }
        $fileUrl = $result['data'];
        $fileName = '1'.$order['pact_url'];
        $file = file_get_contents($fileUrl);
        $path = dirname(dirname(dirname(__FILE__))).'/storage/tmp/'.$fileName;

        file_put_contents($path,$file);
        $uploud_res = AlipayService::upload($fileName,$path);
        if($uploud_res['status']){
            if(file_exists($path)){
                unlink($path);
            }
        }


        return $result;
    }

    /**
     * 文件已全部上传完，申请公证
     * @param $order_id
     * @return void
     */
    public static function notaryReady($contract_id){
        $accessToken = self::getAccessToken();
        $url = config('notarize.apiUrl').'/bussiness/notary_ready';//上传身份证
        $param =[
            "contract_id"=>$contract_id,
        ];
        $result = http_post($url,json_encode($param),['Content-type: application/json;charset=UTF-8','token:'.$accessToken]);
        $result = json_decode($result,true);
        self::requestLog('申请公证',$param,$result);

        return $result;
    }

    /**
     *  单个公证状态查询：/bussiness / notary_query
     * @param $order_id
     * @return void
     */
    public static function notaryQuery($contract_id){
        $accessToken = self::getAccessToken();
        $url = config('notarize.apiUrl').'/bussiness/notary_query';
        $param =[
            "contract_id"=>$contract_id,
        ];
        $result = http_post($url,json_encode($param),['Content-type: application/json;charset=UTF-8','token:'.$accessToken]);
        $result = json_decode($result,true);

        return $result;
    }


    /**
     *  获取更新公证链接：/bussiness /get_notary_link
     * @param $order_id
     * @return void
     */
    public static function get_notary_link($contract_id){
        $accessToken = self::getAccessToken();
        $url = config('notarize.apiUrl').'/bussiness/get_notary_link';
        $param =[
            "contract_id"=>$contract_id,
        ];
        $result = http_post($url,json_encode($param),['Content-type: application/json;charset=UTF-8','token:'.$accessToken]);
        $result = json_decode($result,true);

        return $result;
    }

    /**
     *  取消公证：/bussiness / notary_cancel
     * @param $order_id
     * @return void
     */
    public static function notaryCancel($contract_id){
        $accessToken = self::getAccessToken();
        $url = config('notarize.apiUrl').'/bussiness/notary_cancel';
        $param =[
            "contract_id"=>'20240624163708105156001',
        ];
        $result = http_post($url,json_encode($param),['Content-type: application/json;charset=UTF-8','token:'.$accessToken]);
        $result = json_decode($result,true);

        return $result;
    }


    public static function createAntchain($order){
        if(empty($order['esign_user_id'])){
            $result = EsignService::addPersonAccountID($order['cert_no'],$order['cert_name'],$order['cert_no'],$order['user_mobile']);
            $data1 = $result['data'];
            if(!empty($data1['accountId'])){
                $esign_user_id = $data1['accountId'];
                MemberOther::where('id',$order['uid'])->update(['esign_user_id'=>$esign_user_id]);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署账号创建失败');
            }
        }else{
            $user_mobile = !empty($order['user_mobile'])?$order['user_mobile']:$order['mobile'];
            $esign_user_id = EsignService::updateAccounts($order['esign_user_id'],$user_mobile,$order['cert_name']);
        }

        $shop_user = ShopUser::where('member_id',$order['seller_id'])->select('mechanism','company','faname','esign_shop_id','company_area','agreement','contact_tel','esign_seal_id','companyid')->first();
      return  EsignService::createFlowOneStepShopFour($order,$shop_user,$esign_user_id);
    }

    public static function MakeSign($data)
    {
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string = self::ToUrlParams($data);
        //$string = http_build_query($data);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=".config('wechat.key');
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    public static function ToXml($array){
        if(!is_array($array)|| count($array) <= 0){
            return ;
        }
        $xml = '<xml>';
        foreach ($array as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    public static function FromXml($xml)
    {
        if(!$xml){
            return "xml数据异常！";
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;

    }
    /**
     * 以post方式提交xml到对应的接口url
     *
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param bool $useCert 是否需要证书，默认不需要
     * @param int $second   url执行超时时间，默认30s
     * @throws WxPayException
     */
    public static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
    {
        $header = [
            'Content-type: application/json;'
        ];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $xml);
        if($useCert == true){
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($curl,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($curl,CURLOPT_SSLCERT,'/www/wwwroot/www.doulaizu.com/public/cert/apiclient_cert.pem');
            curl_setopt($curl,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($curl,CURLOPT_SSLKEY, '/www/wwwroot/www.doulaizu.com/public/cert/apiclient_key.pem');
        }
        $result = curl_exec($curl);

        curl_close($curl);
        return $result;
    }



    public static function ToUrlParams($array)
    {
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }

    public static function notices()
    {
        file_put_contents('./pay.txt',file_get_contents('php://input'),FILE_APPEND);
        $xml=file_get_contents('php://input');
        $data=self::FromXml($xml);
        return $data;
    }


}
